package zack.gateway.core.socket.agreement;

import com.alibaba.fastjson2.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.QueryStringDecoder;
import io.netty.handler.codec.http.multipart.Attribute;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**请求参数解析器
 * @author A1793
 */
public class RequestParser {

    private FullHttpRequest request;

    public RequestParser(FullHttpRequest request) {
        this.request = request;
    }

    public String getUri(){

        String uri = request.uri();
        //如果请求参数拼接到了uri上面
        if(uri.indexOf("?") != -1){
            uri = uri.substring(0, uri.indexOf("?"));
        }
        return uri;
    }
    public Map<String,Object> parse() {
        HttpMethod method = request.method();
        String contentType = getContentType();
        Map<String, Object> parammeters = new HashMap<>();

        if (method == HttpMethod.GET) {
            //get请求的额参数都拼接在uri中
            QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri());
            //将 xxx=yyy解析成<k,v>键值对加到map里
            queryStringDecoder.parameters().forEach((k, v) -> {
                parammeters.put(k, v.get(0));
            });
            return parammeters;
        } else if (method == HttpMethod.POST) {
            switch (contentType) {
                case "application/json": {
                    ByteBuf byteBuf = request.content().retain();
                    if (byteBuf.isReadable()) {
                        String content = byteBuf.toString(StandardCharsets.UTF_8);
                        return JSON.parseObject(content);
                    }
                };break;
                case "multipart/form-data": {
                    HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(request);
                    decoder.offer(request);
                    decoder.getBodyHttpDatas().forEach(data -> {
                        Attribute value = (Attribute) data;
                        try {
                            parammeters.put(data.getName(), value.getValue());
                        } catch (Exception e) {
                        }
                        ;
                    });
                };return parammeters;
                default:
                    throw new RuntimeException("未实现的协议类型 Content-Type：" + contentType);
            }
        }
        throw new RuntimeException("未实现的请求类型 HttpMethod：" + method);
    }

    private String getContentType() {
        Optional<Map.Entry<String, String>> header = request.headers()
                .entries().stream().filter(entry -> entry.getKey().equals("Content-Type")).findAny();
        Map.Entry<String, String> entry = header.orElse(null);
        assert entry != null;
        String value = entry.getValue();
        int index = value.indexOf(";");
        if(index >0){
            return value.substring(0,index);
        }else{
            return value;
        }

    }
}
